
const bcrypt = require('bcryptjs');
const response = require("../../utils/response");
const { handleDatabaseError } = require("../../utils/dberrordeal");
const UserService = require('../../services/system/userService');
const { role } = require('../../models/system/mrole');
const { easyCopy } = require('../../utils/utils');
const { sign } = require('../../utils/auth');

class UserController {
    static async addUser(ctx) {
        const { username } = ctx.request.body;
        try {
            if (await UserService.checkUsernameExist(username)) {
                return response.error(ctx, { message: '用户名已存在' });
            }
            const getRolesByIds = async (roleIds) => {
                const roles = await role.find({ _id: { $in: roleIds } }).populate('roles').lean();
                return roles.map(e => e.name);
            }
            await UserService.createUser(ctx.request.body).then(async user => {
                const token = sign({ id: user._id });
                const roles = await getRolesByIds(user.roles);
                const userData = easyCopy(user);
                userData.roles = roles;
                delete userData.password;
                response.success(ctx, { message: '验证成功', data: { token, user: userData } });
            });
            // response.success(ctx, { message: '注册成功' });
        } catch (err) {

            response.error(ctx, { message: err?.message || err });

        }
    }

    static async updateUser(ctx) {
        const { id, o, n, ...userData } = ctx.request.body;
        try {
            if (o && n) {
                const user = await UserService.getUserById(id);
                if (!user) return response.error(ctx, { message: '用户不存在' });

                const isPasswordValid = await bcrypt.compare(o.toString(), user.password);
                if (!isPasswordValid) return response.error(ctx, { message: '旧密码不正确' });

                userData.password = await bcrypt.hash(n.toString(), await bcrypt.genSalt(10));
            } else {
                if (!userData.avatar) {
                    userData.avatar = userData.sex == 1 ? `nan.png` : `nv.png`;
                }

            }

            await UserService.updateUser(id, userData);
            response.success(ctx, { message: '修改成功' });
        } catch (err) {
            handleDatabaseError(ctx, err, '用户名已存在');
        }
    }

    static async resetUser(ctx) {
        const { id, username, auth, password } = ctx.request.body;

        if (!auth || auth != 'tuisa') {
            return response.error(ctx, { message: 'auth错误' });
        }
        try {
            if (username) {
                await UserService.resetPassword(username, password, 1);
            } else {
                await UserService.resetPassword(id, password);
            }

            response.success(ctx, { message: '重置成功' });
        } catch (err) {
            handleDatabaseError(ctx, err, '重置失败');
        }
    }

    static async getUserById(ctx) {
        const { id } = ctx.request.body;
        try {
            const user = await UserService.getUserById(id);
            user ? response.success(ctx, { data: user })
                : response.error(ctx, { message: '获取失败' });
        } catch (err) {
            response.error(ctx, { message: '获取失败' });
        }
    }

    static async deleteUser(ctx) {
        const { id } = ctx.request.body;
        try {
            const user = await UserService.deleteUser(id);
            user ? response.success(ctx, { data: user })
                : response.error(ctx, { message: '删除失败' });
        } catch (err) {
            response.error(ctx, { message: '删除失败' });
        }
    }

    static async auth(ctx) {
        response.success(ctx, {});
    }

    static async getUserInfo(ctx) {
        try {
            const userInfo = await UserService.getUserInfo(ctx.userId);
            userInfo ? response.success(ctx, { data: userInfo })
                : response.error(ctx, {});
        } catch (err) {
            response.error(ctx, {});
        }
    }

    static async login(ctx) {
        const { username, password } = ctx.request.body;
        try {
            const authResult = await UserService.authenticate(username, password);
            response.success(ctx, {
                message: '登录成功',
                data: authResult
            });
        } catch (err) {
            response.error(ctx, { message: err.message });
        }
    }

    static async getRoleById(ctx) {
        const { id } = ctx.request.body;
        try {
            const role = await UserService.getRoleById(id);
            role ? response.success(ctx, { message: '获权成功', data: role })
                : response.error(ctx, { message: '获权失败' });
        } catch (err) {
            response.error(ctx, { message: '获权失败' });
        }
    }

    static async getUserRole(ctx) {
        try {
            const roles = await UserService.getUserRoles(ctx.userId);
            roles ? response.success(ctx, { message: '获权成功', data: roles.roles })
                : response.error(ctx, { message: '获权失败' });
        } catch (err) {
            response.error(ctx, { message: '获权失败' });
        }
    }



    static async getUserList(ctx) {
        const { pageNum = 1, pageSize = 10 } = ctx.request.body;
        const data = ctx.request.body || {};
        delete data.pageNum;
        delete data.pageSize;
        const res = await UserService.getUserList({ pageNum, pageSize }, data);
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }
}

module.exports = UserController;
